const CracoLessPlugin = require('craco-less');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const os = require('os');

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              implementation: require("sass"), // 显式使用 Dart Sass
            },
          },
        ],
      },
    ],
  },
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: { '@primary-color': '#1DA57A' },
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
  webpack: {
    plugins: {
      add: [
        new NodePolyfillPlugin(),
        new ProgressBarPlugin({
          format: '  构建进度 [:bar] :percent (:elapsed秒) :msg',
          clear: false,
          summary: false,
          customSummary: (buildTime) => {
            console.log(`\n✨ 构建完成! 用时: ${buildTime}秒`);
          },
          width: 50
        })
      ]
    },
    configure: (webpackConfig, { env }) => {
      // 移除 ModuleScopePlugin
      webpackConfig.resolve.plugins = webpackConfig.resolve.plugins.filter(
        plugin => !(plugin.constructor.name === 'ModuleScopePlugin')
      );
      
      // 移除之前的 fallback 配置，使用插件提供的 polyfill
      if (webpackConfig.resolve.fallback) {
        delete webpackConfig.resolve.fallback.util;
        delete webpackConfig.resolve.fallback.querystring;
        delete webpackConfig.resolve.fallback.timers;
      }

      // 性能优化配置
      if (env === 'production') {
        // 启用持久化缓存
        webpackConfig.cache = {
          type: 'filesystem',
          buildDependencies: {
            config: [__filename]
          }
        };

        // 修复时序死区问题的配置
        webpackConfig.output = {
          ...webpackConfig.output,
          // 使用更安全的代码生成方式
          environment: {
            arrowFunction: false,
            bigIntLiteral: false,
            const: false,
            destructuring: false,
            dynamicImport: false,
            forOf: false,
            module: false
          }
        };

        // 优化代码分割
        webpackConfig.optimization = {
          ...webpackConfig.optimization,
          splitChunks: {
            chunks: 'all',
            cacheGroups: {
              vendor: {
                test: /[\\/]node_modules[\\/]/,
                name: 'vendors',
                chunks: 'all',
                priority: 10
              },
              tensorflow: {
                test: /[\\/]node_modules[\\/]@tensorflow[\\/]/,
                name: 'tensorflow',
                chunks: 'all',
                priority: 20
              },
              antd: {
                test: /[\\/]node_modules[\\/]antd[\\/]/,
                name: 'antd',
                chunks: 'all',
                priority: 15
              }
            }
          },
          // 使用多线程压缩（限制树莓派的线程数）
          minimizer: webpackConfig.optimization.minimizer.map(minimizer => {
            if (minimizer.constructor.name === 'TerserPlugin') {
              minimizer.options = {
                ...minimizer.options,
                parallel: Math.min(2, os.cpus().length - 1), // 限制并行数量
                terserOptions: {
                  ...minimizer.options.terserOptions,
                  compress: {
                    ...minimizer.options.terserOptions?.compress,
                    // 禁用可能导致时序死区问题的优化
                    hoist_vars: false,
                    hoist_funs: false,
                    sequences: false,
                    // 保持变量声明顺序
                    keep_fnames: true,
                    keep_classnames: true
                  },
                  mangle: {
                    ...minimizer.options.terserOptions?.mangle,
                    // 保持函数和类名
                    keep_fnames: true,
                    keep_classnames: true
                  }
                }
              };
            }
            return minimizer;
          })
        };

        // 设置性能提示阈值（避免警告）
        webpackConfig.performance = {
          maxAssetSize: 512000,
          maxEntrypointSize: 512000,
          hints: 'warning'
        };
      }

      // 查找 sass-loader 规则并修改
      const sassRule = webpackConfig.module.rules.find(
        (rule) => rule.test && rule.test.toString().includes("scss")
      );
      if (sassRule) {
        sassRule.use = sassRule.use.map((loader) => {
          if (loader.loader && loader.loader.includes("sass-loader")) {
            return {
              ...loader,
              options: {
                ...loader.options,
                implementation: require("sass"), // 强制使用 Dart Sass
              },
            };
          }
          return loader;
        });
      }
      
      return webpackConfig;
    },
  },
};